package com.example.logisticsingle.Contorller;

import com.example.logisticsingle.constants.Config;
import com.example.logisticsingle.entity.SSOUser;
import com.example.logisticsingle.login.SSOTokenLoginHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * sso server (for web)
 *
 */
@Controller
public class WebController {

    /**
     * 	首页展示
     * @param model
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/")
    public String index(Model model, HttpServletRequest request, HttpServletResponse response) {

        // login check
        SSOUser ssoUser = SSOTokenLoginHelper.loginCheck(request, response);

        if (ssoUser == null) {
            return "redirect:/login";
        } else {
            model.addAttribute("ssoUser", ssoUser);
            return "index";
        }
    }
    /**
     * 	登录
     * @return
     */
    @GetMapping(value = "/login",produces = {"application/json; charset=UTF-8"})
    public String login(Model model, HttpServletRequest request, HttpServletResponse response) {
        String redirectUrl = request.getParameter(Config.REDIRECT_URL);
        model.addAttribute("errorMsg", request.getParameter("errorMsg"));
        model.addAttribute(Config.REDIRECT_URL, redirectUrl);
        return "login";
    }

    /**
     * Logout
     *
     * @param request
     * @param redirectAttributes
     * @return
     */
    @GetMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {

        // logout
        //SSOTokenLoginHelper.logout(request, response);

        redirectAttributes.addAttribute(Config.REDIRECT_URL, request.getParameter(Config.REDIRECT_URL));
        return "redirect:/login";
    }
}
